<template>
    <div class="article-post-box">
        <h1>发表文章</h1>
        <!-- 标题-->
        <div class="article-title-part">
            <el-input v-model="article.title" placeholder="请输入文章标题" required maxlength="30" clearable show-word-limit/>
        </div>
        <!-- 内容-md编辑器部分 -->
        <div class="article-post-part">
            <mavon-editor
                    ref="mdEditor"
                    v-model="article.content"
                    @htmlCode="htmlCode"
                    @onImageClick="onEditorImageClick"
                    required/>
            <!--  @change="onContentChange" -->
        </div>
        <div class="article-post-settings-part">
            <el-form ref="form" :model="article" label-width="80px">
                <el-form-item label="文章分类" required>
                    <el-select v-model="article.categoryId" placeholder="请选择分类">
                        <el-option
                                v-for="item in categories"
                                :key="item.id"
                                :label="item.name"
                                :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="摘要" required>
                    <el-input
                            type="textarea"
                            :rows="2"
                            placeholder="文章摘要"
                            v-model="article.summary" maxlength="100" clearable show-word-limit>
                    </el-input>
                </el-form-item>
                <el-form-item label="封面" required>
                    <div class="article-cover-selector" @click="showImageSelector">
                        <i class="el-icon-plus" v-if="article.cover === ''"></i>
                        <el-image fit="cover" v-else :src="blog_constant.baseUrl + '/admin/image/' + article.cover"/>
                    </div>
                </el-form-item>
                <el-form-item label="标签" class="label-input-box" required>
                    <el-tag
                            :key="tag"
                            v-for="tag in labels"
                            closable
                            :disable-transitions="false"
                            @close="deleteLabel(tag)">
                        {{tag}}
                    </el-tag>
                    <el-input
                            class="input-new-tag"
                            v-if="labelInputVisible"
                            v-model="labelNewValue"
                            ref="saveTagInput"
                            size="small"
                            @keyup.enter.native="handleLabelInputConfirm"
                    >
                    </el-input>
                    <el-button v-if="!labelInputVisible && !isEnough" class="button-new-tag" size="small"
                               @click="showLabelInput">+ 添加标签
                    </el-button>
                </el-form-item>
            </el-form>
            <!--        文章设置 ：分类、封面、标签 -->
            <!--        发布/草稿/预览按钮-->
        </div>
        <!--        发布/草稿/预览按钮-->
        <div class="article-post-action-bar">
            <div class="action-btn-container">
                <el-button plain size="mini" @click="preView">全屏预览</el-button>
                <el-button plain size="mini" @click="saveArticleDraft">保存草稿</el-button>
                <el-button type="primary" size="mini" @click="commitArticle">发表文章</el-button>
            </div>
        </div>
        <!--  上传封面图片对话框 -->
        <div class="article-post-dialog-box">
            <el-dialog
                    title="选择图片"
                    :visible.sync="isImageSelectorShow"
                    width="50%">
                <div class="image-selector-box">
                    <div class="image-action-bar">
                        <el-upload
                                class="avatar-uploader"
                                action="/admin/image/article"
                                :show-file-list="false"
                                :on-error="onUploadError"
                                :on-success="uploadSuccess"
                                :before-upload="beforeUpload">
                            <el-button>上传图片</el-button>
                        </el-upload>
                    </div>
                    <div class="image-select-list">
                        <el-radio-group v-model="selectedImageIndex">
                            <el-radio-button :label="index" v-for="(item,index) in images" :key="index">
                                <el-image fit="cover" :src="blog_constant.baseUrl + '/admin/image/'+item.url"/>
                            </el-radio-button>
                        </el-radio-group>
                    </div>
                    <div>
                        <!-- 分页组件 -->
                        <el-pagination
                                size="mini"
                                align="center"
                                @size-change="handleSizeChange"
                                @current-change="handleCurrentChange"
                                :current-page="page.current"
                                :page-size="page.size"
                                layout="total, prev, pager, next, jumper"
                                :total="page.total">
                        </el-pagination>
                    </div>
                </div>
                <span slot="footer" class="dialog-footer">
                    <el-button @click="isImageSelectorShow = false" size="mini">取 消</el-button>
                    <el-button type="primary" @click="onImageSelected" size="mini">确 定</el-button>
                </span>
            </el-dialog>
        </div>

    </div>
</template>
<script>
    import {categoryList, getImageList, addArticle} from '@/api/api'
    import editor from '../../../lib/mavon-editor/mavon-editor'
    import '../../../lib/mavon-editor/css/index.css'
    import Vue from 'vue'

    Vue.use(editor)

    export default {
        data() {
            return {
                imageSelectFor: 'article',  // 是上传封面图片还是编辑器上传图片  默认为 article
                selectedImageIndex: '0',// 上传封面选中的图片
                isImageSelectorShow: false,
                isEnough: false, // 控制添加标签按钮的显示
                labelNewValue: '',
                labelInputVisible: false, // 标签是否可见
                labels: [], // 标签集合
                categories: [], // 分类
                article: {
                    summary: '',
                    label: '',
                    categoryId: '',
                    state: '1',
                    cover: '' // 要定义封面字段才可以回显图片
                },
                query: {
                    original: 'article'
                },
                page: {
                    page: 1,
                    size: 24,
                    total: 0
                },
                images: []
            }
        },
        created() {
            this.listCategory()
            this.getImageList()
        },
        methods: {
            // 全屏预览
            preView() {
                this.$refs.mdEditor.toolbar_right_click('read');
            },
            // 保存标签方法抽取
            saveLabel() {
                let tempLabels;
                // 处理标签
                this.labels.forEach((item, index) => {
                    // 取出一个标签，放进 tempLabels
                    tempLabels += item
                    if (index !== this.labels.length - 1) {
                        // 再在标签后添加 -
                        tempLabels += '-'
                    }
                })
                this.article.label = tempLabels
            },
            // 保存草稿
            saveArticleDraft() {
                // 检查内容：标题、内容、分类、摘要、封面、标签
                if (this.article.title === '') {
                    this.$message.error('文章标题不可以为空')
                    return
                }
                if (this.labels.length === 0) {
                    this.$message.error('请添加标签，方便检索分类')
                    return;
                }
                // 处理标签
                this.saveLabel()
                // 修改发布状态为草稿
                this.article.state = '2'
                // 提交新增文章数据
                addArticle(this.article).then(response => {
                    if (response.code === 20000) {
                        this.$message.success(response.message)
                        // 跳转到文章列表页面
                        this.$router.push({path: '/content/article'})
                    } else {
                        this.$message.error(response.message)
                    }
                })
            },
            // 实现发表文章功能
            commitArticle() {
                // 检查内容：标题、内容、分类、摘要、封面、标签
                if (this.article.title === '') {
                    this.$message.error('文章标题不可以为空')
                    return
                }
                if (this.article.content === '') {
                    this.$message.error('文章内容不可以为空')
                    return
                }
                if (this.article.summary === '') {
                    this.$message.error('摘要不可以为空')
                    return
                }
                if (this.article.categoryId === '') {
                    this.$message.error('分类不可以为空')
                    return
                }
                if (this.labels.length === 0) {
                    this.$message.error('请添加标签，方便检索分类')
                    return;
                }
                // 处理标签
                this.saveLabel()
                // 已抽取成一个方法
                // let tempLabels;
                // // 处理标签
                // this.labels.forEach((item, index) => {
                //     // 取出一个标签，放进 tempLabels
                //     tempLabels += item
                //     if (index !== this.labels.length - 1) {
                //         // 再在标签后添加 -
                //         tempLabels += '-'
                //     }
                // })
                // 提交新增文章数据
                addArticle(this.article).then(response => {
                    if (response.code === 20000) {
                        this.$message.success(response.message)
                        // 跳转到文章列表页面
                        this.$router.push({path: '/content/article'})
                    } else {
                        this.$message.error(response.message)
                    }
                })

            },
            htmlCode(status, value) {
                console.log(status)
                console.log(value)
            },
            // 编辑器图片被点击了
            onEditorImageClick() {
                // this.$message.success('编辑器图片点击了')
                this.imageSelectFor = 'article' // 上传类型为封面图片
                this.isImageSelectorShow = true
            },
            // 分页-切换每页显示多少条记录
            handleSizeChange(size) {
                this.page.size = size
                this.getImageList()
            },
            // 分页-切换当前页码
            handleCurrentChange(current) {
                this.page.current = current
                this.getImageList()
            },
            // 上传封面图片之前
            beforeUpload(file) {
                // const isJPG = file.type === 'image/jpeg';
                const isLt2M = file.size / 1024 / 1024 < 2;
                if (!isLt2M) {
                    this.$message.error('上传图片大小不能超过 2MB!');
                }
                return isLt2M;
            },
            // 上传封面图片成功
            uploadSuccess(response) {
                if (response.code === 20000) {
                    this.$message.success(response.message)
                    // 更新封面图片列表
                    this.getImageList()
                }
            },
            // 上传封面图片失败回调
            onUploadError() {
                this.$message.error('图片上传失败')
                this.isImageSelectorShow = true // 打开上传封面图片窗口
            },
            // 获取封面图片列表
            getImageList() {
                getImageList(this.page.current, this.page.size, this.query).then(result => {
                    if (result.code === 20000) {
                        this.images = result.data.records
                        this.page.total = result.data.total
                    }
                })
            },

            // 上传封面图片确定按钮事件
            onImageSelected() {
                // 判断当前的操作是给谁选择图片
                // 如果是文章则插入到文章
                let item = this.images[this.selectedImageIndex]
                if (this.imageSelectFor === 'article') {
                    // 通过 ref 拿到编辑器的链接
                    this.$refs.mdEditor.toolbar_left_addlink('no-link',
                        item.name,
                        this.blog_constant.baseUrl + '/admin/image/' + item.url)
                } else if (this.imageSelectFor === 'cover') {
                    // 如果是封面则作为封面
                    this.article.cover = item.url
                }
                this.isImageSelectorShow = false; // 关闭窗口
            },
            // 打开上传封面图片窗口
            showImageSelector() {
                this.imageSelectFor = 'cover' // 上传类型为封面图片
                this.isImageSelectorShow = true
            },
            // 编辑器改变事件
            // onContentChange(value, render) {
            //     console.log(value)
            //     console.log(render)
            // },
            // 所有分类
            listCategory() {
                categoryList().then(response => {
                    if (response.code === 20000) {
                        // console.log(response)
                        this.categories = response.data
                    }
                })
            },
            // 控制输入框的显示个数,限制最多5个
            showLabelInput() {
                if (this.labels.length < 5) {
                    this.labelInputVisible = true
                } else {
                    this.labelInputVisible = false
                }
            },
            // 添加标签按回车的时候触发事件 ( 记得是“按回车键”才触发 ）
            handleLabelInputConfirm() {
                if (this.labelNewValue === '') {
                    this.$message.error('标签不能为空')
                    this.labelInputVisible = false
                    return
                }
                if (this.labels.length < 5) {
                    this.labels.push(this.labelNewValue);
                    this.labelNewValue = '';
                }
                // 如果加完以后，数量是5，那就隐藏输入框
                if (this.labels.length >= 5) {
                    this.labelInputVisible = false
                    this.isEnough = true
                }
            },
            // 删除标签
            deleteLabel(label) {
                // 从数组里删除一个标签(indexOf() 方法可返回某个指定的字符串值在字符串中首次出现的位置。)
                this.labels.splice(this.labels.indexOf(label), 1)
                if (this.labels.length < 5) {
                    this.isEnough = false
                    this.labelInputVisible = true
                }

            }
        }
    }
</script>
<style>
    /*上传图片按钮*/
    /*.image-action-bar .el-button {*/
    /*    margin-bottom: 10px;*/
    /*}*/

    .el-pagination {
        margin-top: 40px;
    }

    /*去除待选图片的边框*/
    .image-select-list .el-radio-button__inner, .el-radio-button:first-child .el-radio-button__inner {
        border: none;
        padding: 5px;
    }

    /*上传封面图片列表*/
    .image-select-list img {
        width: 104px;
        height: 100px;
        float: left;
        border-radius: 5px;
    }

    /*隐藏封面上传框的标题部分*/
    .article-post-dialog-box .el-dialog__header {
        display: none;
    }

    /*标签输入框*/
    .input-new-tag {
        width: 120px;
    }

    /*标签间距*/
    .label-input-box .el-tag {
        margin-left: 6px;
    }

    /*封面*/
    .article-cover-selector {
        cursor: pointer;
        width: 200px;
        height: 140px;
        border: #DCDFE6 solid 1px;
        border-radius: 5px;
        text-align: center;
    }

    .article-cover-selector img {
        width: 200px;
        height: 140px;
    }

    /* 封面十字 */
    .article-cover-selector i {
        font-size: 20px;
        color: #DCDFE6;
        line-height: 140px;
    }

    /*摘要输入框宽度*/
    .article-post-settings-part .el-textarea {
        width: 400px;
    }

    /*修改编辑器高度*/
    .markdown-body {
        height: 600px;
        margin-bottom: 20px;
        margin-top: 20px;
    }

    .article-title-part {
        margin-top: 20px;

    }

    /*让编辑器滚动到顶部定住*/
    .article-post-part .v-note-op {
        position: sticky;
        top: 0;
    }

    .article-post-settings-part {
        height: 300px;
        margin-bottom: 100px;
        z-index: 99;

    }

    .action-btn-container {
        float: right;
        margin-right: 50px;
        padding: 10px;
    }

    /*发表按钮在底部定住*/
    .article-post-action-bar {
        position: fixed;
        bottom: 20px;
        right: 30%;
        z-index: 2000;
    }
</style>